app.factory('rssReader', ['$http', 'configReader', function rssReaderFactory($http, configReader){
  var rssConfig;
  var rssData;

  function getConfig() {
    var def = jQuery.Deferred();

    if (rssConfig) {
      def.resolve(rssConfig);
    }
    else {
      configReader.read('rss').then(function(config) {
        rssConfig = config;
        def.resolve(rssConfig);
      }, function(error, statusCode) {
        def.reject(error, statusCode);
      });
    }

    return def.promise();
  }

  function read(url) {
    var def = jQuery.Deferred();

    getConfig().then(function(rssConfig) {
      if (!url && !rssConfig.url) {
        def.reject(new TypeError('url is not provided'));
      }

      var parseUrl = '/parse/xmlToJson/' + encodeURIComponent(url || rssConfig.url);
      $http.get(parseUrl)
        .success(function(data, config) {
          def.resolve(data, config);
        }).error(function(data, statusCode) {
          def.reject(data, statusCode);
        });
    });
    return def.promise();
  }

  return {
    read: read
  };
}]);